package com.huawei.app.demo.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huawei.app.demo.AppConstants;
import com.huawei.app.demo.MsgHandler;
import com.huawei.app.demo.R;
import com.huawei.app.demo.adapter.ContactAdapter;
import com.huawei.app.demo.msg.ConfEndMsgCallback;
import com.huawei.app.demo.util.LogUtils;
import com.huawei.app.httpapi.HttpApiResult;
import com.huawei.app.httpapi.IdeaHubHttpApiUtils;
import com.huawei.app.httpapi.MsgRspCallback;
import com.huawei.app.httpapi.ThreadPools;

/**
 * 会议
 *
 * @since 2021-01-20
 */
public class ConferenceFragment extends CustomFragment {

    private static final String TAG = ConferenceFragment.class.getSimpleName();
    private Context context;
    private View rootView;
    private List<Map<String,String>> dataList;
    private ContactAdapter dataAdapter;
    private MsgRspCallback msgCallback = new LdapSearchMsgCallback();
    private MsgRspCallback confEndMsgCallback = null;
    private boolean initDataFinish = false;

    @Override
    public String getTitle() {
        return "会议";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (this.rootView != null) {
            return rootView;
        }
        this.context = getContext();
        this.rootView = inflater.inflate(R.layout.fragment_conference, container, false);
        this.confEndMsgCallback = new ConfEndMsgCallback(context);

        // init view
        Button openConfPage = rootView.findViewById(R.id.openConfPage);
        Button createConfBtn = rootView.findViewById(R.id.createConf);
        Button queryContactBtn = rootView.findViewById(R.id.queryContact);
        ListView contactList = rootView.findViewById(R.id.contactList);

        // init event
        openConfPage.setOnClickListener(this);
        createConfBtn.setOnClickListener(this);
        queryContactBtn.setOnClickListener(this);

        // init data
        this.dataList = new ArrayList<>();
        this.dataAdapter = new ContactAdapter(context, dataList);
        contactList.setAdapter(dataAdapter);

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!initDataFinish && IdeaHubHttpApiUtils.getInstance().isLoginSuccess()) {
            queryContactList(0);
            initDataFinish = true;
        }
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.openConfPage: {
                openConfPage();
                break;
            }
            case R.id.createConf: {
                createConf();
                break;
            }
            case R.id.queryContact: {
                queryContactList(0);
                break;
            }
            default: {
                break;
            }
        }
    }

    /**
     * 打开会议界面
     */
    public void openConfPage() {
        LogUtils.getInstance().i(TAG, "openConfPage begin.");

        Intent intent = new Intent("com.device.action.THIRDAPP_START_ACTIVITY");
        intent.putExtra("activityName", "Meeting");
        context.sendBroadcast(intent, "com.device.permission.THIRDAPP");

        LogUtils.getInstance().i(TAG, "openConfPage end.");
    }

    /**
     * 创建会议
     */
    public void createConf() {
        LogUtils.getInstance().i(TAG, "createConf begin.");

        ThreadPools.run(new Runnable() {
            @Override
            public void run() {
                IdeaHubHttpApiUtils.getInstance().registerMsgCall(confEndMsgCallback);

                Map<String,String> resultMap = getLocalConfInfo();
                String confId = resultMap.get("confId");
                String confPwd = "";
                int type = 1; // 1为视频呼叫, 2为音频呼叫

                HttpApiResult result = IdeaHubHttpApiUtils.getInstance().createConf(confId, confPwd, type);
                if (result.isSuccess()) {
                    LogUtils.getInstance().i(TAG, "create conf success.");
                } else {
                    LogUtils.getInstance().i(TAG, "create conf failed.");

                    Message msg = Message.obtain();
                    msg.what = MsgHandler.SHOW_TOAST;
                    msg.obj = "create conf failed.";
                    msgHandler.sendMessage(msg);
                }
            }
        });

        LogUtils.getInstance().i(TAG, "createConf end.");
    }

    /**
     * 获取本地会场信息
     * @return
     */
    private Map<String, String> getLocalConfInfo() {
        Map<String,String> resultMap = new HashMap<>();
        String confId = "";
        String confPwd = "";

        HttpApiResult result = IdeaHubHttpApiUtils.getInstance().getLocalConfInfo();
        if (result.isSuccess()) {
            confId = result.getValueByPath("localVMR.confID");
            confPwd = result.getValueByPath("localVMR.passwd");
        }
        resultMap.put("confId", confId);
        resultMap.put("confPwd", confPwd);
        return resultMap;
    }

    /**
     * 刷新通讯录内容
     */
    public void queryContactList(final int time) {
        ThreadPools.schedule(new Runnable() {
            @Override
            public void run() {
                IdeaHubHttpApiUtils.getInstance().registerMsgCall(msgCallback);

                // 查询通讯录信息
                HttpApiResult apiResult = IdeaHubHttpApiUtils.getInstance().searchLdapAddr();
                if (!apiResult.isSuccess()) {
                    LogUtils.getInstance().e(TAG, "searchLdapAddr failed, apiResult is " + apiResult);
                    IdeaHubHttpApiUtils.getInstance().unregisterMsgCall(msgCallback);

                    Message msg = Message.obtain();
                    msg.what = MsgHandler.SHOW_TOAST;
                    msg.obj = "通讯录查询失败.";
                    msgHandler.sendMessage(msg);
                    return;
                }
            }
        }, time, TimeUnit.MILLISECONDS);
    }

    class LdapSearchMsgCallback implements MsgRspCallback {
        @Override
        public int getMsgId() {
            return AppConstants.MSG_LDAP_SEARCH_RSP;
        }

        @Override
        public String getMsgName() {
            return "MSG_LDAP_SEARCH_RSP";
        }

        @Override
        public void handleMsg(JSONObject msgObj) {
            if (msgObj == null) {
                return;
            }
            IdeaHubHttpApiUtils.getInstance().unregisterMsgCall(msgCallback);

            // 获取通讯录查询结果
            HttpApiResult apiResult = IdeaHubHttpApiUtils.getInstance().getLdapAddrResult();
            if (!apiResult.isSuccess()) {
                LogUtils.getInstance().e(TAG, "getLdapAddrResult failed, apiResult is " + apiResult);

                Message msg = Message.obtain();
                msg.what = MsgHandler.SHOW_TOAST;
                msg.obj = "通讯录查询失败.";
                msgHandler.sendMessage(msg);
                return;
            }

            JSONObject dataObj = apiResult.getData();
            if (dataObj == null) {
                LogUtils.getInstance().i(TAG, "getLdapAddrResult success, but data is empty.");

                Message msg = Message.obtain();
                msg.what = MsgHandler.SHOW_TOAST;
                msg.obj = "通讯录内容为空.";
                msgHandler.sendMessage(msg);
                return;
            }
            JSONArray ldapList = dataObj.getJSONArray("LdapList");
            if (ldapList == null || ldapList.isEmpty()) {
                LogUtils.getInstance().i(TAG, "getLdapAddrResult success, but LdapList is empty.");

                Message msg = Message.obtain();
                msg.what = MsgHandler.SHOW_TOAST;
                msg.obj = "通讯录内容为空.";
                msgHandler.sendMessage(msg);
                return;
            }

            // 刷新缓存中的通讯录数据
            List<Map<String,String>> tmpList = new ArrayList<>();
            for (int i=0; i<ldapList.size(); i++) {
                JSONObject itemObj = ldapList.getJSONObject(i);
                Map<String,String> map = new HashMap<>();
                map.put("contactName", itemObj.getString("site"));
                map.put("contactNumber", itemObj.getString("sipNum"));
                tmpList.add(map);
            }
            dataList.clear();
            dataList.addAll(tmpList);

            // 刷新界面
            msgHandler.post(new Runnable() {
                @Override
                public void run() {
                    dataAdapter.notifyDataSetChanged();
                    Toast.makeText(context, "通讯录查询成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}
